import { getRequest } from './api'

export const getMenus = (router, token) => {
  // console.log('routes:')
  // console.log(router.options.routes.length)
  // console.log(router.options.routes)
  if (router.options.routes.length <= 1) {
    getRequest('/menus?token=' + token).then(data => {
      if (data) {
        //存入sessionStore
        // console.log('get menus:')
        // console.log(data)
        window.sessionStorage.setItem('menus', JSON.stringify(data.menus))
        initRoutes(router, data.menus)
        // console.log('get router')
        // console.log(router)
      }
    })
  }

}

export const initRoutes = (router, menus) => {
  // console.log('window menus:')
  // console.log(menus)
  if (!(menus == '' || menus == null || menus == undefined)) { // "",null,undefined
    //格式化
    let fmtRoutes = formatRoutes(menus)
    // console.log(fmtRoutes)
    //添加到路由
    fmtRoutes.forEach((aRoute) => {
      router.options.routes.push(aRoute)
      router.addRoute(aRoute)
      // console.log(aRoute)
    })
    // router.addRoutes(fmtRoutes)
  }
}

export const formatRoutes = (routes) => {
  let fmtRoutes = []
  for (let i in routes) {
    let {
      path,
      component,
      name,
      iconCls,
      children,
    } = routes[i]
    if (children && children instanceof Array) {
      children = formatRoutes(children)
    }
    let fmtRouter = {
      path: path,
      name: name,
      iconCls: iconCls,
      children: children,
      component (resolve) {
        if (component.startsWith('Emp')) {
          require(['../views/emp/' + component + '.vue'], resolve)
        } else if (component.startsWith('Per')) {
          require(['../views/per/' + component + '.vue'], resolve)
        } else if (component.startsWith('Sal')) {
          require(['../views/sal/' + component + '.vue'], resolve)
        } else if (component.startsWith('Sta')) {
          require(['../views/sta/' + component + '.vue'], resolve)
        } else if (component.startsWith('Sys')) {
          require(['../views/sys/' + component + '.vue'], resolve)
        } else {
          require(['../views/' + component + '.vue'], resolve)
        }
      }
    }
    // console.log(fmtRouter);
    fmtRoutes.push(fmtRouter)
  }
  return fmtRoutes
}
